package com.seeyon.apps.kkARPEvent.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.log.CtpLogFactory;
import org.apache.commons.logging.Log;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class KKOAtokenUtil {

    private static final Log log = CtpLogFactory.getLog(KKOAtokenUtil.class.getSimpleName());
    private static final String URL = AppContext.getSystemProperty("OAtokeb.TokenUrl");
    private static final String USERNAME = AppContext.getSystemProperty("OAtokeb.userName");
    private static final String PASSWORD = AppContext.getSystemProperty("OAtokeb.password");

    private static final String UNIT_URL = "http://10.1.20.98/seeyon/rest/GetDepart/MemberListByPage";
    private static final String DEPART_URL = "http://10.1.20.98/seeyon/rest/GetDepart/getSubDepart";
    private static final String ONEDEPART_URL = "http://10.1.20.98/seeyon/rest/GetDepart/Depart";
    private static final String DEPARTMEMBER_URL = "http://10.1.20.98/seeyon/rest/GetDepart/getDepartMember";
    private static final String MEMBERINFO_URL = "http://10.1.20.98/seeyon/rest/GetDepart/getMemberInfo";


    /**
     * 获取Seeyon Rest账号token
     *
     * @return 返回获取的Token字符串
     * @throws IOException 抛出可能的异常
     */
    public static String seeyonToken() {
        log.info("客开日志-----------【seeyonToken】start");
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost post = new HttpPost(URL);
            post.setHeader("Content-Type", "application/json");

            // 构建请求体
            Map<String, String> requestBody = new HashMap<>();
            requestBody.put("userName", USERNAME);
            requestBody.put("password", PASSWORD);
            String jsonRequestBody = JSON.toJSONString(requestBody);

            // 设置请求体
            post.setEntity(new StringEntity(jsonRequestBody, "UTF-8"));
            log.info("客开日志-----------【seeyonToken】发送的请求体: " + jsonRequestBody);

            // 发送请求并解析响应
            try (CloseableHttpResponse response = httpClient.execute(post)) {
                log.info("客开日志-----------【seeyonToken】请求体（json格式）:" + response);
                HttpEntity entity = response.getEntity();
                log.info("entity:" + entity);
                if (entity != null) {
                    String responseString = EntityUtils.toString(entity, "UTF-8");
                    log.info("客开日志-----------【seeyonToken】获取Token的响应: " + responseString);

                    // 解析响应
                    JSONObject jsonResponse = JSON.parseObject(responseString);
                    if (jsonResponse.containsKey("id")) { // 修改为获取 "id" 字段
                        String token = jsonResponse.getString("id");
                        log.info("客开日志-----------【seeyonToken】OA-token==> " + token);
                        return token;
                    } else {
                        log.error("客开日志-----------【seeyonToken】获取Token失败: " + responseString);
                    }
                }
            }
        } catch (Exception e) {
            log.error("客开日志-----------【seeyonToken】获取Seeyon Token失败", e);
        }
        log.info("客开日志-----------【seeyonToken】end");
        return null;
    }


    /**
     * 获取所有人员信息
     *
     * @param params 请求参数，包含 offset 和 limit
     * @return 人员信息的 Map 列表
     * @throws IOException 如果请求失败
     */
    public static List<Map<String, Object>> getAllOrgAccounts(Map<String, Object> params) {
        // 获取 Token
        String token = seeyonToken();
        log.info("客开日志-----------【getAllOrgAccounts】start");

        // 创建 HTTP 客户端
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            // 创建 POST 请求
            HttpPost post = new HttpPost(UNIT_URL);
            log.info("客开日志-----------【getAllOrgAccounts】请求 URL: " + UNIT_URL);

            // 设置请求头
            post.setHeader("Content-Type", "application/json");
            post.setHeader("token", token); // 传递 Token

            // 将请求参数 params 转换为 JSON 字符串
            String jsonParams = JSON.toJSONString(params);  // 使用 FastJSON 将 Map 转换为 JSON 字符串
            StringEntity entity = new StringEntity(jsonParams, "UTF-8");
            post.setEntity(entity); // 设置请求体

            log.info("客开日志-----------【getAllOrgAccounts】请求体: " + jsonParams);

            // 发送请求并处理响应
            try (CloseableHttpResponse response = httpClient.execute(post)) {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    String responseString = EntityUtils.toString(responseEntity, "UTF-8");
                    log.info("客开日志-----------【getAllOrgAccounts】响应内容: " + responseString);

                    // 将 JSON 字符串解析为 List<Map<String, Object>>
                    List<Map<String, Object>> responseList = JSON.parseObject(responseString, List.class);
                    log.info("客开日志-----------【getAllOrgAccounts】responseList: " + responseList);
                    return responseList; // 返回解析后的数据
                }
            }
        } catch (Exception e) {
            log.error("客开日志-----------【getAllOrgAccounts】获取所有单位信息失败: " + e.getMessage(), e);
        }

        log.info("客开日志-----------【getAllOrgAccounts】end");
        return null; // 如果发生异常，返回 null
    }

    /**
     * 获取一级部门信息
     */
    public static List<Map<String, Object>> getOrgDepartmentsByOne() {
        // 获取 Token
        String token = seeyonToken();
        log.info("客开日志-----------【getAllOrgDepartments】start");
        // 创建 HTTP 客户端
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建 POST 请求
            HttpPost post = new HttpPost(ONEDEPART_URL);
            log.info("客开日志-----------【getAllUnit】请求 URL: " + ONEDEPART_URL);

            // 设置请求头
            post.setHeader("Content-Type", "application/json");
            post.setHeader("token", token); // 传递 Token

            // 发送请求并处理响应
            try (CloseableHttpResponse response = httpClient.execute(post)) {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    String responseString = EntityUtils.toString(responseEntity, "UTF-8");
                    log.info("客开日志-----------【getAllUnit】响应内容: " + responseString);

                    // 将 JSON 字符串解析为 List<Map<String, Object>>
                    List<Map<String, Object>> responseList = JSON.parseObject(responseString, List.class);
                    log.info("客开日志-----------【getAllUnit】responseList: " + responseList);
                    return responseList; // 返回解析后的数据
                }
            }


        }catch (Exception e){
            log.error("客开日志-----------【getAllOrgDepartments】获取一级部门信息失败: " + e.getMessage(), e);
        }
        log.info("客开日志-----------【getAllUnit】end");
        return null; // 如果发生异常，返回 null
    }


    /**
     * 获取单位信息
     */
    public static List<Map<String, Object>> getAllUnit(Map<String, Object> params) {
        // 获取 Token
        String token = seeyonToken();
        log.info("客开日志-----------【getAllUnit】start");

        // 创建 HTTP 客户端
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            // 创建 POST 请求
            HttpPost post = new HttpPost(DEPART_URL);
            log.info("客开日志-----------【getAllUnit】请求 URL: " + DEPART_URL);

            // 设置请求头
            post.setHeader("Content-Type", "application/json");
            post.setHeader("token", token); // 传递 Token

            // 将请求参数 params 转换为 JSON 字符串
            String jsonParams = JSON.toJSONString(params);  // 使用 FastJSON 将 Map 转换为 JSON 字符串
            StringEntity entity = new StringEntity(jsonParams, "UTF-8");
            post.setEntity(entity); // 设置请求体

            log.info("客开日志-----------【getAllUnit】请求体: " + jsonParams);

            // 发送请求并处理响应
            try (CloseableHttpResponse response = httpClient.execute(post)) {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    String responseString = EntityUtils.toString(responseEntity, "UTF-8");
                    log.info("客开日志-----------【getAllUnit】响应内容: " + responseString);

                    // 将 JSON 字符串解析为 List<Map<String, Object>>
                    List<Map<String, Object>> responseList = JSON.parseObject(responseString, List.class);
                    log.info("客开日志-----------【getAllUnit】responseList: " + responseList);
                    return responseList; // 返回解析后的数据
                }
            }
        } catch (Exception e) {
            log.error("客开日志-----------【getAllUnit】获取所有单位信息失败: " + e.getMessage(), e);
        }

        log.info("客开日志-----------【getAllUnit】end");
        return null; // 如果发生异常，返回 null
    }

    /**
     * 查询部门的成员
     */
    public static List<Map<String, Object>> getAllOrgDepartments(Map<String, Object> params) {
        // 获取 Token
        String token = seeyonToken();
        log.info("客开日志-----------【getAllUnit】start");

        // 创建 HTTP 客户端
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            // 创建 POST 请求
            HttpPost post = new HttpPost(DEPARTMEMBER_URL);
            log.info("客开日志-----------【getAllUnit】请求 URL: " + DEPARTMEMBER_URL);

            // 设置请求头
            post.setHeader("Content-Type", "application/json");
            post.setHeader("token", token); // 传递 Token

            // 将请求参数 params 转换为 JSON 字符串
            String jsonParams = JSON.toJSONString(params);  // 使用 FastJSON 将 Map 转换为 JSON 字符串
            StringEntity entity = new StringEntity(jsonParams, "UTF-8");
            post.setEntity(entity); // 设置请求体

            log.info("客开日志-----------【getAllUnit】请求体: " + jsonParams);

            // 发送请求并处理响应
            try (CloseableHttpResponse response = httpClient.execute(post)) {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    String responseString = EntityUtils.toString(responseEntity, "UTF-8");
                    log.info("客开日志-----------【getAllUnit】响应内容: " + responseString);

                    // 将 JSON 字符串解析为 List<Map<String, Object>>
                    List<Map<String, Object>> responseList = JSON.parseObject(responseString, List.class);
                    log.info("客开日志-----------【getAllUnit】responseList: " + responseList);
                    return responseList; // 返回解析后的数据
                }
            }
        } catch (Exception e) {
            log.error("客开日志-----------【getAllUnit】获取所有单位信息失败: " + e.getMessage(), e);
        }

        log.info("客开日志-----------【getAllUnit】end");
        return null; // 如果发生异常，返回 null
    }

    /**
     * 批量查询人员中等信息
     * @param userIds
     * @return
     */
    public static List<Map<String, Object>> getAllOrgUsers(List<String> userIds) {
        // 获取 Token
        String token = seeyonToken();
        log.info("客开日志-----------【getAllUnit】start");

        // 创建 HTTP 客户端
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            // 创建 POST 请求
            HttpPost post = new HttpPost(MEMBERINFO_URL);
            log.info("客开日志-----------【getAllUnit】请求 URL: " + MEMBERINFO_URL);

            // 设置请求头
            post.setHeader("Content-Type", "application/json");
            post.setHeader("token", token); // 传递 Token

            // 将请求参数 params 转换为 JSON 字符串
            String jsonParams = JSON.toJSONString(userIds);  // 使用 FastJSON 将 Map 转换为 JSON 字符串
            StringEntity entity = new StringEntity(jsonParams, "UTF-8");
            post.setEntity(entity); // 设置请求体

            log.info("客开日志-----------【getAllUnit】请求体: " + jsonParams);

            // 发送请求并处理响应
            try (CloseableHttpResponse response = httpClient.execute(post)) {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    String responseString = EntityUtils.toString(responseEntity, "UTF-8");
                    log.info("客开日志-----------【getAllUnit】响应内容: " + responseString);

                    // 将 JSON 字符串解析为 List<Map<String, Object>>
                    List<Map<String, Object>> responseList = JSON.parseObject(responseString, List.class);
                    log.info("客开日志-----------【getAllUnit】responseList: " + responseList);
                    return responseList; // 返回解析后的数据
                }
            }
        } catch (Exception e) {
            log.error("客开日志-----------【getAllUnit】获取所有单位信息失败: " + e.getMessage(), e);
        }

        log.info("客开日志-----------【getAllUnit】end");
        return null; // 如果发生异常，返回 null
    }
}
